// Arup Guha
// 11/7/06
// Solution for CIS 3362 DES Project

// There are many weaknesses in this solution due to my laziness!
// All of the constants in the algorithm should be stored in final
// static variables, but I just wanted to read in the information
// from the files instead of hard-coding them.

// Also, the key should stay the same for encrypting one file, but
// the blocks must change. This hasn't been indicated clearly.

import java.io.*;
import java.util.Arrays;

public class DES{
	
	private int[] key;
	private int[][] roundkeys;
	private int[] block;
	
	private int[][][] stables;
	private int[] IP;
	private int[] IPInv;
	private int[] E;
	private int[] PC2;
	private int[] P;
	private int[] PC1;
	private int[] keyshifts;
	
	private boolean decryption;
	
	// Reads all the information from the file I created based on the order
	// the values were stored in the file. My original posted file had some
	// errors in it, because some zeroes were stored as captial O's. I fixed 
	// those issues in the file and have posted the corrected file with this
	// solution.
	public DES(int[] thekey, boolean decryptbool) throws Exception {
		decryption = decryptbool;
		key = new int[64];
		stables = new int[8][4][16];
		IP = new int[64];
		IPInv = new int[64];
		E = new int[48];
		PC2 = new int[48];
		P = new int[32];
		PC1 = new int[56];
		keyshifts = new int[16];
		block = new int[64];
		
		// Sets the key to what was passed in.
		for (int i=0; i<64; i++)
			key[i] = thekey[i];
		
		//Scanner fin = new Scanner(new File("destables.txt"));
		// Reads in the initial permutation matrix.
		//for (int i=0; i<64; i++)
		//	IP[i] = fin.nextInt();
		IP = new int[]{58, 50, 42,  34, 26, 18, 10, 2,
		60, 52, 44, 36, 28, 20, 12, 4,
		62, 54, 46, 38, 30, 22, 14, 6,
		64, 56, 48, 40, 32, 24, 16, 8,
		57, 49, 41, 33, 25, 17,  9, 1,
		59, 51, 43, 35, 27, 19, 11, 3,
		61, 53, 45, 37, 29, 21, 13, 5,
		63, 55, 47, 39, 31, 23, 15, 7};
		
		// Reads in the inverse of the initial permutation matrix.
		//for (int i=0; i<64; i++)
		//	IPInv[i] = fin.nextInt();
		IPInv = new int[]{
		40, 8, 48, 16, 56, 24, 64, 32,
		39, 7, 47, 15, 55, 23, 63, 31,
		38, 6, 46, 14, 54, 22, 62, 30,
		37, 5, 45, 13, 53, 21, 61, 29,
		36, 4, 44, 12, 52, 20, 60, 28,
		35, 3, 43, 11, 51, 19, 59, 27,
		34, 2, 42, 10, 50, 18, 58, 26,
		33, 1, 41, 9, 49, 17, 57, 25};
		
		// Expansion matrix used in each round.
		//for (int i=0; i<48; i++)
		//	E[i] = fin.nextInt();	
		E = new int[]{
		32, 1, 2, 3, 4, 5,
		4, 5, 6, 7, 8, 9,
		8, 9, 10, 11, 12, 13,
		12, 13, 14, 15, 16, 17,
		16, 17, 18, 19, 20, 21,
		20, 21, 22, 23, 24, 25,
		24, 25, 26, 27, 28, 29,
		28, 29, 30, 31, 32, 1};
		// The permutation matrix P used in each round.
		//for (int i=0; i<32; i++)
		//	P[i] = fin.nextInt();
		
		P = new int[]{
		16,  7, 20, 21,
		29, 12, 28, 17,
		1, 15, 23, 26,
		5, 18, 31, 10,
		2, 8, 24, 14,
		32, 27, 3, 9,
		19, 13, 30, 6,
		22, 11, 4, 25};

 		// Reads in the 8 S-boxes!
 		//for (int i=0; i<8; i++) {
 		
 		//	for (int j=0; j<64; j++) {
 		//		stables[i][j/16][j%16] = fin.nextInt();
 		//	}
 		//}
 		stables[0][0] = new int[]{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7};
 		stables[0][1] = new int[]{0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8};
 		stables[0][2] = new int[]{4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0};
		stables[0][3] = new int[]{15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13};


		stables[1][0] = new int[]{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10};
		stables[1][1] = new int[]{3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5};
		stables[1][2] = new int[]{0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15};
		stables[1][3] = new int[]{13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9};


		stables[2][0] = new int[]{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8};
		stables[2][1] = new int[]{13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1};
		stables[2][2] = new int[]{13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7};
		stables[2][3] = new int[]{1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12};


		stables[3][0] = new int[]{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15};
		stables[3][1] = new int[]{13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9};
		stables[3][2] = new int[]{10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4};
		stables[3][3] = new int[]{3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14};


		stables[4][0] = new int[]{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9};
		stables[4][1] = new int[]{14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6};
		stables[4][2] = new int[]{4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14};
		stables[4][3] = new int[]{11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3};


		stables[5][0] = new int[]{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11};
		stables[5][1] = new int[]{10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8};
		stables[5][2] = new int[]{9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6};
		stables[5][3] = new int[]{4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13};


		stables[6][0] = new int[]{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1};
		stables[6][1] = new int[]{13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6};
		stables[6][2] = new int[]{1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2};
		stables[6][3] = new int[]{6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12};



		stables[7][0] = new int[]{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7};
		stables[7][1] = new int[]{1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2};
		stables[7][2] = new int[]{7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8};
		stables[7][3] = new int[]{2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11};

      		
      		// Reads in PC1, used for the key schedule.
      		//for (int i=0; i<56; i++)
      		//	PC1[i] = fin.nextInt();
		PC1 = new int[]{
		57, 49, 41, 33, 25, 17, 9,
		1, 58, 50, 42, 34, 26, 18,
		10, 2, 59, 51, 43, 35, 27,
		19, 11, 3, 60, 52, 44, 36,
		63, 55, 47, 39, 31, 23, 15,
		7, 62, 54, 46, 38, 30, 22,
		14, 6, 61, 53, 45, 37, 29,
		21, 13, 5, 28, 20, 12, 4};

		// Reads in PC2 used for the round keys.	
		//for (int i=0; i<48; i++)
		//	PC2[i] = fin.nextInt();
		PC2 = new int[]{
		14, 17, 11, 24, 1, 5,
		3, 28, 15, 6, 21, 10,
		23, 19, 12, 4, 26, 8,
		16,  7, 27, 20, 13, 2,
		41, 52, 31, 37, 47, 55,
		30, 40, 51, 45, 33, 48,
		44, 49, 39, 56, 34, 53,
		46, 42, 50, 36, 29, 32};

		// Reads in the shifts used for the key between each round.
		//for (int i=0; i<16; i++)
		//	keyshifts[i] = fin.nextInt();
		keyshifts = new int[]{1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};


		//fin.close();
	}
	
	// Sets a block based on the string of bits. The string is guaranteed
	// to only have characters '0' and '1'.
	public void setBlock(int[] bits) {
		for (int i=0; i<64; i++)
			block[i] = bits[i];
	}
	
	// Prints out a block with spaces after every 8 characters on one line.
	public void print(FileWriter fout) throws Exception {
		/*
	 	for (int i=0; i<64; i++) {
			if (i%8 == 0) fout.write(" ");		
			fout.write(""+block[i]);
		}
		
		fout.write("\n");
		*/
		String encryptedtext = DESthread.binaryToRad64(block);
		// USED IN DECRYPTION
		if(decryption)
		{
			fout.write("Decrypted: " + Main.shortbinaryToRad64(block) + "\n");
			System.out.println(Main.shortbinaryToRad64(block));
		}
		
		
		// SADLY DOESN"T ACTUALLY PRINT THE REAL KEY YOU HAVE TO DO THAT WITH DESthread
		if(encryptedtext.equals("jogjQrIyHp4"))
		{
			fout.write("VICTORY!\n");
			for (int i=0; i<64; i++) {
				if (i%8 == 0) fout.write(" ");		
					fout.write(""+key[i]);
			}
			fout.write("\n");
			
			System.out.println("VICTORY!");
			for (int i=0; i<64; i++) {
				if (i%8 == 0) fout.write(" ");		
				System.out.print(""+key[i]);
			}
			System.out.println();
			System.exit(0);
		}
		
	}
	
	// Encrypts the current block.
	public void encrypt() {
		
		// Permute the block with the initial permutation.
		block = Permute(block, IP);
		
		// Run 16 rounds.
		for (int i=0; i<16; i++) {
			round(i);			
		}
		
		// Supposed to switch halves at the end and invert the initial
		// permutation.
		switchHalves();
		block = Permute(block, IPInv);
	}
	
	// Switches the left half of the current block with the right half.
	public void switchHalves() {
		int[] temp = new int[32];
		
		// We're just doing a regular swap between 32 bits...
		
		for (int i=0; i<32; i++)
			temp[i] = block[i];
			
		for (int i=0; i<32; i++)
			block[i] = block[32+i];
			
		for (int i=32; i<64; i++)
			block[i] = temp[i-32];
	}
	
	// Permutes the bits in original according to perm and
	// returns this permutation of the original bits.
	public int[] Permute(int[] original, int[] perm) {
		
		
		int[] ans = new int[original.length];
		
		// Note: We subtract 1 from perm[i] because in the tables, the
		// permutations are 1-based, instead of 0-based.
		for (int i=0; i< perm.length; i++)
			ans[i] = original[perm[i]-1];
		return ans;		
	}
	
	// Takes the block of bits in whole from index start to index end, 
	// inclusive and cyclicly left-shifts them by numbits number of bits.
	public void leftShift(int[] whole, int start, int end, int numbits) {
		int size = end-start+1;
		int[] temp = new int[size];
		
		// Copy the bits into temp in their new order.
		for (int i=0; i<temp.length; i++) 
			temp[i] = whole[start+(numbits+i)%size];	
		
		// Copy them back into the original array in the order we stored them
		// in temp, with the appropriate offset, start.
		for (int i=0; i<temp.length; i++)
			whole[start+i] = temp[i];
	}
	
	public void printArray(int[] array) {
		for (int i=0; i<array.length; i++) {
			if (i%8 == 0) System.out.print(" ");
			System.out.print(array[i]);
		}
		System.out.println();
	}
	
	// Runs round num of DES.
	public void round(int num) {
		int[] left = new int[32];
		int[] right = new int[32];
		
		// Copy in the left and right blocks into temporary arrays.
		for (int i=0; i<32; i++)
			left[i] = block[i];
		for (int i=0; i<32; i++)
			right[i] = block[32+i];
		
		// Expand the right block.
		int[] expanded = E(right);
		
		// This is the XOR we want.
		int[] xorans = XOR(expanded, roundkeys[num]);

		// Run the s-boxes on all the appropriate "blocks".
		int[] sboxout = Sboxes(xorans);
		
		// Permute the S-box output.
		int[] fout = Permute(sboxout, P);
		
		// Then do the necessary XOR.
		fout = XOR(fout, left);
		
		// Copy the blocks back into their proper place!
		for (int i=0; i<32; i++)
			block[i] = right[i];
		for (int i=0; i<32; i++)
			block[32+i] = fout[i]; 
	}
	
	// Expand the 32 bits and return the corresponding 48 bits.
	public int[] E(int[] bits) {
		int[] ans = new int[48];
		
		// Our permutation function doesn't work for this, so it's coded here.
		for (int i=0; i<48; i++)
			ans[i] = bits[E[i]-1];
		return ans;	
	}
	
	// Returns the XOR of the bit streams a and b.
	public int[] XOR(int[] a, int[] b) {
		int[] ans = new int[a.length];
		for (int i=0; i<a.length; i++)
			ans[i] = (a[i]+b[i])%2;
		return ans;
	}
	
	// Returns the output of putting the 48 bit input through the
	// 8 S-boxes.
	public int[] Sboxes(int[] input) {
		int[] ans = new int[32];
		
		for (int i=0; i<8; i++) {
			
			// Just hard-coded this part. There doesn't seem to be a more
			// elegant way...
			int row = 2*input[6*i] + input[6*i+5];
			int col = 8*input[6*i+1]+4*input[6*i+2]+2*input[6*i+3]+input[6*i+4];
			
			int temp = stables[i][row][col];
			
			// We have to store the base-10 answer in binary, so we strip off the
			// bits one-by-one, in the usual manner from the least to most significant.
			for (int j=3; j>=0; j--) {
				ans[4*i+j] = temp%2;
				temp /= 2;
			}
		}
		return ans;
		
	}
	
	// Set up the keys for each round.
	public void setKeys() {
		roundkeys = new int[16][48];
		
		// Set the original key with PC1.	
		key = Permute(key, PC1);
		
		// Go through and set the round keys using the process by which they
		// are supposed to be computed.
		for (int i=0; i<16; i++) {
			
			// Supposed to left-shift both halves by the appropriate amount,
			// based on the round.
			leftShift(key, 0, 27, keyshifts[i]);
			leftShift(key, 28, 55, keyshifts[i]);
			
			// Now, just copy in the (i+1)th round key.
			for (int j=0; j<48; j++) {
				roundkeys[i][j] = key[PC2[j]-1];
			}				
		}
	}
	// Set up the keys for each round.
	public void reverseKeys() {
        boolean PRINT = false;
		int rows = 16;
        int cols = 48;
        int[][] reverse = new int[rows][cols];
        if (PRINT)System.out.println("Round Keys:");
        for(int i = rows-1; i >= 0; i--) {
        	if (PRINT)System.out.println(Arrays.toString(roundkeys[i]));
            for(int j = cols-1; j >= 0; j--) {
                reverse[rows-1-i][j] = roundkeys[i][j];
            }
        }
        if (PRINT)System.out.println("Reverse Round Keys");
        roundkeys = reverse;
        if (PRINT)
        {
        		for(int i = rows-1; i >= 0; i--) {
        			System.out.println(Arrays.toString(roundkeys[i]));
        		}
        }
	}
	
	// Converts the string version of the key in HEX to binary which is
	// stored in an integer array of size 64...thus, the check bits are
	// included here.
	public int[] getKey(String thekey) {
		int[] ans = new int[64];
		thekey = thekey.toLowerCase();
		// Go through all 16 characters.
		for (int i=0; i<16; i++) {
			int val = (int)(thekey.charAt(i));
			
			// We need to assign value separately if it is a digit or a letter.
			if ('0' <= val && val <= '9')
				val = val - '0';
			else
				val = val - 'a' + 10;
			
			// Peel off the binary bits as before...
			for (int j=3; j>=0; j--) {
				ans[4*i+j]=val%2;
				val /= 2;
			}
		}
		
		return ans;
	}
}